package handler

import (
	"context"
	"google.golang.org/protobuf/types/known/emptypb"
	"kuangstudy-mall/srvs/goods-srv/global"
	"kuangstudy-mall/srvs/goods-srv/model"
	"kuangstudy-mall/srvs/goods-srv/proto"
)

// 查询分类 用于首页
func (h *GoodsServiceHandler) FindCategoryListToIndex(ctx context.Context, req *proto.CategoryInfoRequest) (*proto.CategoryListResponse, error) {
	var categoryList []model.Category
	tx := global.DB.Where("status = 1")
	if req.IsIndex > -1 {
		tx = tx.Where("is_index", req.IsIndex)
	}
	tx.Order("sorted").Find(&categoryList)
	var response proto.CategoryListResponse
	response.Total = int32(len(categoryList))

	var dataList []*proto.CategoryResponse
	for _, category := range categoryList {
		dataList = append(dataList, &proto.CategoryResponse{
			Id:       category.ID,
			Name:     category.Name,
			Img:      category.Img,
			Icon:     category.Icon,
			Sorted:   category.Sorted,
			ParentId: category.ParentId,
			IsIndex:  category.IsIndex,
		})
	}
	response.Data = dataList
	// gorm查询轮播
	return &response, nil
}

/*
查询所有分类
*/
func (h *GoodsServiceHandler) FindCategoryList(context.Context, *emptypb.Empty) (*proto.CategoryAllListResponse, error) {
	var categoryList []model.Category
	tx := global.DB.Where("status = 1")
	tx.Order("sorted").Find(&categoryList)
	var response proto.CategoryAllListResponse
	response.Data = h.tree(0, categoryList)
	// gorm查询轮播
	return &response, nil
}

func (h *GoodsServiceHandler) tree(parentId uint64, categoryList []model.Category) []*proto.CategoryResponse {
	var dataList []*proto.CategoryResponse
	for _, category := range categoryList {
		if category.ParentId == parentId {
			dataList = append(dataList, &proto.CategoryResponse{
				Id:       category.ID,
				Name:     category.Name,
				Img:      category.Img,
				Icon:     category.Icon,
				Sorted:   category.Sorted,
				ParentId: category.ParentId,
				IsIndex:  category.IsIndex,
				Children: h.tree(category.ID, categoryList),
			})
		}
	}
	return dataList
}
